<!--
 * @Date         : 2024-03-01 20:29:20
 * @LastEditTime : 2024-09-13 21:57:11
 * @description  : 答题页面
-->
<script setup>
import Header from "../components/Header-imitate.vue";
import Popup from "../components/Popup.vue";
import PopupCode from "../components/PopupCode.vue";
import imgT from "../assets/1708570277524.png";
import {
  autoSubTrainExam,
  getTrainExamProblem,
  subTrainAnswer,
  subTrainExam,
} from "@/api";
import router from "@/router";
import { onlyExecuteOnce } from "@/utils";

const RefPopup = ref("");
const RefPopupEnd = ref("");
const RefHeader = ref("");
const RefPopupCode = ref("");
// 答题提示
const tipList = ref([
  {
    color: "#f1a72e",
    text: "已答题",
  },
  {
    color: "#652E1B",
    text: "在答",
  },
  {
    color: "#FFFFFF",
    text: "未答",
  },
  // {
  //   color: "#F1A72E",
  //   text: "标记",
  // },
]);
let problemList = ref([]);
let allProblemList = ref([]);
let isSidebar = ref(false);
let afootPro = ref({}); //正在答题
// 弹窗剩余
const onPopupShow = (config) => {
  RefPopup.value.show(config);
};
const onTipPopupShow = () => {
  RefPopupCode.value.show();
};

// 获取题目
const getList = async () => {
  let newProblemObj = JSON.parse(sessionStorage.getItem("problemList")) || "";
  isSidebar.value = false;
  let problemArr = [];
  if (newProblemObj) {
    problemArr = newProblemObj;
  } else {
    let res = await getTrainExamProblem();
    let { problem, exam_info } = res.data;
    sessionStorage.setItem("problemList", JSON.stringify(problem));
    sessionStorage.setItem("problemInfo", JSON.stringify(exam_info));
    problemArr = problem;
  }
  let list = [];
  let allArr = [];
  let allArrProIndex = -1;
  let probleNumber = 0;
  let upperlist = "一二三四五六七八九十".split("");
  for (const key in problemArr) {
    if (Object.hasOwnProperty.call(problemArr, key)) {
      const element = problemArr[key];
      let newArr = element.map((item, index, arr) => {
        allArrProIndex = allArrProIndex + 1;
        return {
          ...item,
          probleTitle: key,
          probleNumber: upperlist[probleNumber],
          problemNum: arr.length,
          problemIndex: index + 1,
          allArrProIndex: allArrProIndex,
          isSign: item?.isSign || false, //是否标记
          answerValue: item?.answerValue || [], //答案
        };
      });
      list.push({
        probleTitle: key,
        list: newArr,
      });
      allArr.push(...newArr);
      probleNumber++;
    }
  }
  allProblemList.value = allArr; //所欲题目
  problemList.value = list;
  afootPro.value = allArr[0]; //当前题目
  isSidebar.value = true;
};
// 更新数据
const upDataLsit = () => {
  let newProblemObj = JSON.parse(sessionStorage.getItem("problemList")) || "";
  isSidebar.value = false;
  let problemArr = newProblemObj;
  let list = [];
  let allArr = [];
  let allArrProIndex = -1;
  let probleNumber = 0;
  let upperlist = "一二三四五六七八九十".split("");
  for (const key in problemArr) {
    if (Object.hasOwnProperty.call(problemArr, key)) {
      const element = problemArr[key];
      let newArr = element.map((item, index, arr) => {
        allArrProIndex = allArrProIndex + 1;
        return {
          probleNumber: upperlist[probleNumber],
          ...item,
          probleTitle: key,
          problemNum: arr.length,
          problemIndex: index + 1,
          allArrProIndex: allArrProIndex,
          isSign: item?.isSign || false, //是否标记
          answerValue: item?.answerValue || [], //答案
        };
      });
      list.push({
        probleTitle: key,
        list: newArr,
      });
      allArr.push(...newArr);
      probleNumber++;
    }
  }
  allProblemList.value = allArr; //所欲题目
  problemList.value = list;
};
// 获取验证码
const getCodeVlue = (value) => {
  onSubExam(value);
};

// 选择题目
const onActivePro = async (v) => {
  await onsubTrainAnswer();
  afootPro.value = v;
  upDataLsit();
};
// 下一题
const onNextPro = async () => {
  let alllist = allProblemList.value;
  let index = afootPro.value?.allArrProIndex + 1;
  if (alllist.length > index) {
    await onsubTrainAnswer();
    upDataLsit();
    afootPro.value = alllist[index];
  } else {
    ElMessage({
      showClose: true,
      message: "当前已是最后一道题",
      type: "warning",
    });
  }
};
// 上一题
const onLastPro = () => {
  let alllist = allProblemList.value;
  let index = afootPro.value?.allArrProIndex - 1;
  if (index < 0) {
    ElMessage({
      showClose: true,
      message: "当前已是第一道题",
      type: "warning",
    });
    return;
  }
  if (alllist.length > index) {
    afootPro.value = alllist[index];
    upDataLsit();
  } else {
    ElMessage({
      showClose: true,
      message: "当前已是第一道题",
      type: "warning",
    });
  }
};
// 标记
const onSign = () => {
  let newProblemObj = JSON.parse(sessionStorage.getItem("problemList")) || "";
  let key = afootPro.value.probleTitle;
  let id = afootPro.value.id;
  afootPro.value.isSign = !afootPro.value.isSign;
  newProblemObj[key] = newProblemObj[key].map((item) => {
    if (item.id == id) {
      return {
        ...item,
        isSign: !item?.isSign,
      };
    } else {
      return item;
    }
  });
  sessionStorage.setItem("problemList", JSON.stringify(newProblemObj));
};
// 编辑答案
const onAnswerChange = (value) => {
  value = value.sort();
  let newProblemObj = JSON.parse(sessionStorage.getItem("problemList")) || "";
  let key = afootPro.value.probleTitle;
  let id = afootPro.value.id;
  newProblemObj[key] = newProblemObj[key].map((item) => {
    if (item.id == id) {
      return {
        ...item,
        answerValue: value,
      };
    } else {
      return item;
    }
  });
  sessionStorage.setItem("problemList", JSON.stringify(newProblemObj));
};

// 点击 交卷
const onClickSub = async () => {
  await onsubTrainAnswer();
  upDataLsit();
  let list = allProblemList.value;
  var count = list.reduce(function (acc, cur) {
    return cur.answerValue?.length <= 0 ? acc + 1 : acc;
  }, 0);
  // 还有多少题没有答
  if (count > 0) {
    onPopupShow({
      text: `<div style="color:#333;font-size:16px;font-weight:600;">检测到您剩余<span style="color:#f00;font-weight:600;">${count}道题</span>未做完，<span style="color:#f00;font-weight:600;">是否</span>确认交卷？</div>`,
    });
  } else {
    // onTipPopupShow();
    onSubExam();
  }
};
// 交卷
const onSubExam = async (value) => {
  let { exam_log_id, exam_id } =
    JSON.parse(sessionStorage.getItem("problemInfo")) || "";
  let startTime = sessionStorage.getItem("startTime");
  let usetime = startTime ? (+new Date() - startTime) / 1000 : 0;
  debugger;
  await onsubTrainAnswer();
  subTrainExam({
    exam_id,
    exam_log_id,
    usetime,
    // key: value.codeKey,
    // captcha: value.code,
  }).then((res) => {
    ElMessage({
      showClose: true,
      message: "模拟考试结束",
      type: "warning",
    });
    RefPopupCode.value.hide();
    sessionStorage.removeItem("problemList");
    sessionStorage.removeItem("startTime");
    sessionStorage.removeItem("endTime");
    router.replace("/typePage");
  });
};
//  自动提交结果
async function autoSubTrain() {
  let { exam_log_id, exam_id } =
    JSON.parse(sessionStorage.getItem("problemInfo")) || "";
  let startTime = sessionStorage.getItem("startTime");
  let usetime = (+new Date() - startTime) / 1000;
  await onsubTrainAnswer();
  autoSubTrainExam({
    exam_id,
    exam_log_id,
    usetime,
  }).then((res) => {
    ElMessage({
      showClose: true,
      message: "模拟考试结束",
      type: "warning",
    });
    sessionStorage.removeItem("problemList");
    sessionStorage.removeItem("startTime");
    sessionStorage.removeItem("endTime");
    router.replace("/typePage");
  });
}
// 提交答案
const onsubTrainAnswer = async () => {
  let { exam_log_id, exam_id } =
    JSON.parse(sessionStorage.getItem("problemInfo")) || "";
  let { id, answerValue } = afootPro.value;
  let answer = answerValue?.join("") || "";
  // if (!answer) return;
  let res = await subTrainAnswer({
    problem_id: id,
    answer,
    exam_id,
    exam_log_id,
  });
};

const onPopupOk = () => {
  // onTipPopupShow();
  onSubExam();
};
const onPopupNo = () => {
  console.log("onPopupno");
};
const end = (value) => {
  if (value) {
    onlyExecuteOnce(() => {
      RefPopupEnd.value.show({
        text: `距离考试剩余3分钟！请把握好时间`,
        type: 2,
      });
    });
  } else {
    autoSubTrain();
  }
};
const onAnswerClick = () => {
  if (afootPro.value.probleTitle == "单选题") {
    afootPro.value.answerValue = [];
  }
};
onMounted(() => {
  getList();
});
</script>

<template>
  <div class="AnswerPage">
    <Header ref="RefHeader" title="中成药介绍练习考试" @end="end">
      <!-- <el-button
        type="primary"
        color="#F1A72E"
        style="color: #ffffff; margin-left: 20px"
        @click="onClickSub"
        >交卷</el-button
      > -->
    </Header>
    <div class="main">
      <div class="sidebar">
        <!-- 答题提示 -->
        <div class="tip">
          <div class="tip-one" v-for="(v, i) in tipList" :key="i">
            <div class="block" :style="{ background: v.color }"></div>
            {{ v.text }}
          </div>
        </div>
        <!-- 题目 -->
        <div class="topic" key="">
          <div
            class="topic_one"
            v-for="(item, index) in problemList"
            :key="index"
          >
            <div class="title">
              {{ item.probleTitle }} (共{{ item.list.length }}道题)
            </div>
            <div class="list">
              <div
                class="list_block"
                v-for="(v, i) in item.list"
                :key="v.id"
                @click="onActivePro(v)"
                :class="{
                  active: v.id === afootPro.id,
                  signStyle: v.isSign,
                  answerStyle: v?.answerValue.length > 0,
                }"
              >
                {{ i + 1 }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 当前题目 -->
      <div class="content" :key="afootPro.id">
        <div class="type-tip">
          <div class="tip-title">
            {{ afootPro.probleNumber }}、
            <template v-if="afootPro.probleTitle != '单选题'">
              {{
                afootPro.probleTitle
              }}，每题的备选项中，有2个或2个以上符合题意。
            </template>
            <template v-else>
              {{
                afootPro.probleTitle
              }}，题目分为若干组，每组题目基于同一个临床情景、病例、实例或者案例展开。
            </template>
          </div>
          <div class="tip-txt">
            {{
              afootPro.probleTitle == "单选题"
                ? "每题的备选项中，只有1个最符合题意。"
                : "错选、少选不得分"
            }}
          </div>
        </div>
        <div class="problom-block">
          <!-- <div class="left">
            <el-image
              style="width: 420px; height: 100%"
              :src="afootPro.problem_img"
              fit="contain"
              :preview-src-list="[afootPro.problem_img]"
              :max-scale="1.5"
              :min-scale="0.75"
            />
            <ImageMsg />
          </div> -->
          <div class="right">
            <div class="right-main">
              <!-- <div class="pro_num">第 {{ afootPro.problemIndex }} 题：</div> -->
              <div class="pro_title">{{ afootPro.title }}</div>
              <div class="pro_title">{{ afootPro.subtitle }}</div>
              <el-checkbox-group
                v-model="afootPro.answerValue"
                fill="#ccc"
                @change="onAnswerChange"
              >
                <el-checkbox
                  @click="onAnswerClick"
                  v-for="(item, index) in afootPro.ans"
                  :key="index"
                  :label="item.number"
                  :value="item.number"
                  >{{ item.number }}. {{ item.content }}</el-checkbox
                >
              </el-checkbox-group>
            </div>
            <div class="bottom">
              <el-button type="primary" color="#652E1B" @click="onLastPro"
                >上一题</el-button
              >
              <!-- <el-button
                type="primary"
                color="#F1A72E"
                style="color: #ffffff"
                @click="onSign"
                >{{ afootPro.isSign ? "已标记" : "标记" }}</el-button
              > -->
              <el-button type="primary" color="#652E1B" @click="onNextPro"
                >下一题</el-button
              >
              <el-button
                type="primary"
                color="#f00"
                style="color: #ffffff; margin-left: 20px"
                @click="onClickSub"
                >交卷</el-button
              >
              <!-- 
          <el-button
            type="primary"
            color="#F1A72E"
            style="color: #ffffff"
            @click="onClickSub"
            >交卷</el-button
          > -->
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 弹窗   剩余题目 -->
  <Popup ref="RefPopup" @ok="onPopupOk" @hide="onPopupNo" />
  <Popup ref="RefPopupEnd" @ok="onPopupOk" />
  <PopupCode @codeVlue="getCodeVlue" ref="RefPopupCode" />
</template>
<style lang="scss" scoped>
.AnswerPage {
  background: #855c4c;
  box-sizing: border-box;
  height: 100vh;
  min-width: 100vw;
  overflow: auto;
  .main {
    overflow: hidden;
    // margin: 0 10px 10px 10px;
    // border-radius: 10px;
    // background: #f6eee8;
    box-sizing: border-box;
    height: 88vh;
    // padding: 20px;
    display: flex;
    justify-content: space-between;
    .sidebar {
      width: 18vw;
      height: 100%;
      min-width: 270px;
      flex-shrink: 0;
      background: #f7f0eb;
      .tip {
        display: flex;
        padding: 20px;
        flex-wrap: wrap;
        .tip-one {
          flex-shrink: 0;
          display: flex;
          align-items: center;
          font-weight: 500;
          font-size: 12px;
          color: #666666;
          line-height: 25px;
          text-align: left;
          font-weight: 600;
          margin-right: 10px;
          .block {
            width: 14px;
            height: 14px;
            margin-right: 4px;
            border-radius: 2px 2px 2px 2px;
          }
        }
      }
      .topic {
        overflow-y: auto;
        height: calc(100% - 75px);
        .topic_one {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          padding: 0 0 40px;
          .title {
            width: 100%;
            background: #652e1b;
            color: #fff;
            font-size: 14px;
            font-weight: 600;
            padding: 5px 10px;
            letter-spacing: 2px;
          }
          .list {
            display: grid;
            margin-top: 20px;
            grid-template-columns: repeat(5, 1fr);
            width: 70%;
            .list_block {
              cursor: pointer;
              flex-shrink: 0;
              width: 32px;
              margin-bottom: 10px;
              height: 32px;
              background: #ffffff;
              border-radius: 2px 2px 2px 2px;
              text-align: center;
              line-height: 28px;
              margin-right: 32px;
              margin-top: 5px;
              border: 1px solid #ccc;
            }

            .answerStyle {
              background: #f1a72e;
              color: #fff;
              border: 1px solid #f1a72e;
            }
            .signStyle {
              background: #f1a72e;
              color: #fff;
              border: 1px solid #f1a72e;
            }
            .active {
              background: #652e1b !important;
              color: #fff;
              border: 1px solid #652e1b;
            }
          }
        }
      }
    }
    .content {
      background: #fff;
      height: 100%;
      flex: 1;
      box-sizing: border-box;
      padding: 20px;
      display: flex;
      flex-direction: column;
      .type-tip {
        padding-bottom: 30px;
        margin-bottom: 20px;
        flex-shrink: 0;
        border-bottom: 2px dashed var(--el-border-color);
        .tip-title {
          font-weight: bold;
          font-size: 20px;
          color: #652e1b;
          line-height: 20px;
          text-align: left;
          font-weight: 600;
        }
        .tip-txt {
          font-size: 20px;
          margin-top: 10px;
          color: #652e1b;
          line-height: 20px;
          text-align: left;
          font-weight: 600;
          text-indent: 40px;
        }
      }
      .problom-block {
        flex: 1;
        overflow: auto;
        display: flex;
        justify-content: space-around;
        .left {
          flex: 1;
          height: 100%;
          padding: 10px;
          box-sizing: border-box;
          display: flex;
          font-weight: 600;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          border-right: 2px dashed var(--el-border-color);
        }
        ::v-deep .right {
          position: relative;
          flex: 1;
          padding: 30px;
          padding-bottom: 100px;
          box-sizing: border-box;
          font-weight: 600;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          height: 100%;
          .right-main {
            flex: 1;
            overflow: auto;
            .pro_num {
              font-size: 20px;
              font-weight: 600;
              margin-bottom: 10px;
            }
            .pro_title {
              font-size: 20px;
              font-weight: 600;
              text-indent: 30px;
            }
            .el-checkbox {
              width: 20%;
              margin: 20px;
              height: auto;
              white-space: normal;
              line-height: 1.5;
              word-break: break-all;
              align-items: baseline;
              flex-shrink: 0;
            }
            .el-checkbox__label {
              line-height: 1.9;
              font-weight: 600;
              font-size: 18px;
            }
          }
        }
      }
      .bottom {
        padding-top: 10px;
        position: absolute;
        width: 100%;
        bottom: 0;
        right: 0;
        padding: 10px;
        display: flex;
        background: #fff;
        justify-content: space-around;
        align-items: center;
        z-index: 22;
        .el-button {
          transform: scale(1.2);
        }
      }
    }
  }
}
.is-checked {
  .el-checkbox__label {
    background: #000;
    color: #666 !important;
  }
}

::-webkit-scrollbar {
  width: 10px;
  height: 10px;
  background-color: #f5f5f5;
  border-radius: 5px;
}

/* 设置滚动条滑块的背景色和圆角 */
::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 5px;
}

/* 设置滚动条滑块在悬停状态下的背景色和圆角 */
::-webkit-scrollbar-thumb:hover {
  background-color: #999;
  border-radius: 5px;
}

/* 设置滚动条轨道的背景色和圆角 */
::-webkit-scrollbar-track {
  background-color: #f5f5f5;
  border-radius: 5px;
}

/* 设置滚动条轨道在悬停状态下的背景色和圆角 */
::-webkit-scrollbar-track:hover {
  background-color: #ccc;
  border-radius: 5px;
}
</style>
